package tcp.heartbeat;

import java.io.IOException;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.List;

import networkdescriptor.NetworkDescriptor;

public class HeartbeatHandler implements Runnable{

	private HeartBeatManager manager ;
	private HeartbeatLostHandler handler;
	
	public HeartbeatHandler(HeartBeatManager manager, HeartbeatLostHandler heartbeatlost){
		this.manager = manager;
		this.handler = heartbeatlost;
	}
	
	public void run() {
		System.out.println(this.getClass().getSimpleName()+" : Scheduler calling");
		NetworkDescriptor details = null;
		try {
			

			List items = this.manager.getWatchedFileStores("HB_NETWORK_DESCRIPTOR") ;
			if(items != null && items.size() > 0){
				for(int i = 0; i < items.size(); i++){
					Socket heartBeatTester = new Socket();
					details = (NetworkDescriptor)items.get(i);
					System.out.println(details.getHostname()+":"+details.getPortNumber());
					heartBeatTester.connect(new InetSocketAddress(details.getHostname(),details.getPortNumber()));
					if(!heartBeatTester.isConnected()){
						System.out.println("Remove from overwatch");
						this.manager.removeUnresponseFileStoreNode(details.getHostname()+":"+details.getPortNumber());
					}else{
						System.out.println("Heartbeat check for node:"+details.getHostname()+" Successful");
					}
					heartBeatTester.close();
				}
			}
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}catch(ConnectException e){
			System.out.println("Couldn't connect, delete");
			String serverId = details.getHostname()+":"+details.getPortNumber();
			this.manager.removeUnresponseFileStoreNode(serverId);
			this.handler.handleHeartBeatLost(serverId);
		}catch(IOException e){
			e.printStackTrace();
		}
		
		
	}

	
	
}
